﻿using System.Web.Mvc;
using System.Web.Routing;
using ProgrammingSchool.Core.Factories;
using ProgrammingSchool.Infrastructure.Filters.Authorize;
using ProgrammingSchool.Infrastructure.Filters.Exceptions;
using Microsoft.Practices.Unity;
using ProgrammingSchool.Infrastructure.Factories;
using ProgrammingSchool.Core.Interfaces;
using ProgrammingSchool.Core.Services;
using System;
using Web.Mvc.ModelBinders;
using System.Web.Helpers;

namespace ProgrammingSchool
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private static volatile IUnityContainer _container;

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new GlobalAuthorizeAttribute());
            filters.Add(new HandleErrorAttribute());
            filters.Add(new ExeptionHandlingAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            InitializeContainer();
            RegisterModelBinders();
        }

        private static void InitializeContainer()
        {
            if (_container == null)
            {
                var containerFactory = new DefaultContainerFactory();
                _container = containerFactory.CreateContainer();
            }

            var controllerFactory = new UnityControllerFactory(_container);
            ControllerBuilder.Current.SetControllerFactory(controllerFactory);
        }

        private static void RegisterModelBinders()
        {
            ModelBinders.Binders.DefaultBinder = new AntiXssModelBinder();
        }
    }
}